#include "GAmodSettings.hpp"


int GAmodSettings::add_setting(char *key,GAmodObjWrapper *val)
{
    string stringK(key);

    this->mySettings.insert(make_pair(stringK,val));

    return 0;
}

const GAmodObjWrapper *GAmodSettings::get_setting(char *key)
{
    string sk(key);
    GAmodObjWrapper *val;

    val = this->mySettings[sk];
    //if(val.size()>0) return val.c_str();
    //else return NULL;
    return val;
}

template<class MyClass> int GAmodSettings::get_value(char *key, MyClass &retVal)
{
	TemplateGAmodObjWrapper<MyClass> *val;

	string sk(key);

    val = (TemplateGAmodObjWrapper<MyClass>*)this->mySettings[sk];
    //if(val.size()>0) return val.c_str();
    //else return NULL;
    if (val)
    {
    	retVal = val->value;
    	return 1;
    }

    return 0;
}

int GAmodSettings::get_size()
{
    return mySettings.size();
}

int GAmodSettings::read_from_file(const char *path,const char *filter)
{
    FILE *fin;
    char buff[2048];
    string str,key,value,tmp;
    unsigned int n=0,j;

    fin = fopen(path,"r");
    if(!fin)
    {
        IF_DBG_VERB( perror("[ERROR] GAmodSettings::read_from_file: "); )
        return -1;
    }

    mySettings.clear();

    int i=0;
    while(fgets(buff,1023,fin))
    {

        tmp.assign(buff);
        str.clear();
        for(j=0; j<tmp.size(); j++)
            if(isalnum(tmp[j]) || ispunct(tmp[j])) str.push_back(tmp[j]);

        //printf("%d = <%s>\n",i++,str.c_str());

        if(str[0] == '#') continue;

        string::size_type loc = str.find( '=', 0 );
        if(loc !=string::npos)
        {
                key = str.substr(0,loc);
                value = str.substr(loc+1,str.size());
                //printf("KEY = <%s>\n",key.c_str());
                //printf("VALUE = <%s>\n",value.c_str());
        }
        else continue;

        if(filter)  //FILTRO.NOME = VALORE
        {
            string::size_type loc2 = key.find( '.', 0 );
            if(loc2 != string::npos)
            {
                    tmp = key.substr(0,loc2);
                    //printf("ID  = <%s>\n",tmp.c_str());
                    key = key.substr(loc2+1,key.size());
                    //printf("REAL KEY = <%s>\n",key.c_str());
                    if(tmp.compare(filter)!=0) continue;
            }
            else
            {
                IF_DBG_INFO(printf("[WARN] GAmodSettings::read_from_file: riga %d, impossibile trovare filtro\n",i);)
                continue;
            }
        }

        //IF_DBG_VERB(printf("Aggiungo <%s,%s>\n",key.c_str(),value.c_str());)


        GAmodObjWrapper *strsett;
        //strsett = new GAmodStrSetting(value);
        strsett = new TemplateGAmodObjWrapper<string>(value);
        this->mySettings.insert(make_pair(key,strsett));
    }

    return n;
}

void GAmodSettings::clear() {

    map<std::string,GAmodObjWrapper *>::iterator it;

    for(it = mySettings.begin(); it!= mySettings.end(); it++)
    {
        delete (*it).second;
    }

    mySettings.clear();
}
